import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../global/Global.dart';
import '../util/LogUtil.dart';
import 'dart:convert';

class Storage {
  static Future<void> setString(key, value) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }

  static Future<String> getString(key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(key);
  }

  static Future<void> remove(key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove(key);
  }

  static Future<void> clear() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.clear();
  }

  /**
   * 获取当前接口返回的userId的方法的封装
   * */
  static Future<String> getUserId() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var strStor = sp.getString(Global.LOGINDATA);
    if (strStor == null) {
      LogUtil.v("没有缓存的数据。。。");
      return "";
    }
    var logBean = json.decode(strStor); // Json 字符串转化成 Map 类型
    String userId = logBean["zx"]["userId"];
    LogUtil.v("userId:$userId");
//    if (userId == null) {
//      return "";
//    }
    return userId;
  }


  /**
   * 获取当前接口返回的userId的方法的封装
   * */
  static Future<String> getToken() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var strStor = sp.getString(Global.LOGINDATA);
    if (strStor == null) {
      LogUtil.v("没有缓存的数据。。。");
      return "";
    }
//    var logBean = json.decode(strStor); // Json 字符串转化成 Map 类型
//    String access_token = logBean["zx"]["access_token"];
//    LogUtil.v("access_token:$access_token");

    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
//    LogUtil.v("有缓存strStor:$strStor");
    var logBean = json.decode(strStor);
    var access_token = "Bearer "+logBean["access_token"];

    // LogUtil.v("access_token：$access_token");

    return access_token;  // token 需要添加前缀 “Bearer ” 有空格哦
  }

  /**
   * 获取当前接口返回的userId的方法的封装
   * */
  static Future<String> getId() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var strStor = sp.getString(Global.LOGINDATA);
    if (strStor == null) {
      LogUtil.v("没有缓存的数据。。。");
      return "";
    }
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
//    LogUtil.v("有缓存strStor:$strStor");
    var logBean = json.decode(strStor);
    String id = logBean["id"];

    LogUtil.v("获取到的id：$id");
    return id;
  }
}
